<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    @close="closeEvent"
  >
    <el-form ref="form" label-width="120px" :model="form" :rules="rules">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select
          v-model="form.manager"
          placeholder="请选择负责人"
          @focus="focusEvent"
        >
          <el-option
            v-for="i in userList"
            :key="i.id"
            :label="i.username"
            :value="i.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitBtn">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companydepartmentPost,
  companydepartmentPut
} from '@/api/departments'
export default {
  props: {
    initData: {
      // 原始树形数据
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: 'add',
      dialogFormVisible: false,
      userList: [], // 员工简单信息
      curItem: '', // 当前点击项数据
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rules, val, callback) => {
              // 从原始树形数据中筛选出当前pid为 点击项id的数据, 也就是点击项的子集
              const newArr = this.initData.filter((item) => {
                if (this.mode === 'add') {
                  return item.pid === this.curItem.id
                } else if (this.mode === 'edit') {
                  return (
                    item.pid === this.curItem.pid && item.id !== this.curItem.id
                  )
                }
              })
              // 遍历点击项的子集, 确认每项name属性 与用户填写的值是否相同, 返回true代表有重复,返回false代表没有
              const bol = newArr.some((item) => {
                return item.name === val
              })
              bol ? callback(new Error('部门重复:' + val)) : callback()
            }
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rules, val, callback) => {
              // 所有编码都不能重复
              const bol = this.initData.some((item) => {
                if (this.mode === 'add') {
                  return item.code === val
                } else if (this.mode === 'edit') {
                  return item.code === val && item.id !== this.curItem.id
                }
              })
              bol ? callback(new Error('编码重复:' + val)) : callback()
            }
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  computed: {
    title() {
      return { add: '添加新部门', edit: '查看/编辑部门' }[this.mode]
    }
  },
  mounted() {
    this.$bus.$on('showDialog', (curItem, mode) => {
      this.dialogFormVisible = true
      this.curItem = curItem // 赋值
      this.form.pid = curItem.id // 将id 传给form中的pid
      this.mode = mode
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(curItem))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('showDialog') // 销毁TreeItem中传来的方法,避免累加执行
  },
  methods: {
    async focusEvent() {
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
      }
    },
    submitBtn() {
      this.$refs.form.validate(async(val) => {
        if (val) {
          if (this.mode === 'add') {
            await companydepartmentPost(this.form) // 调用api添加数据,错误信息已经在request中统一处理
            this.$message.success('添加成功')
          } else if (this.mode === 'edit') {
            await companydepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          this.dialogFormVisible = false // 关闭dialog
          this.$parent.getData()
          // 调用父级中的方法 this.$parent
        }
      })
    },
    closeEvent() {
      this.$refs.form.resetFields() // 清空表单数据和表单验证
      this.form = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}
</style>
